//	--------------------------------------------------------------------
//	Copyright(C) 2006,2007 Zhao Yukun. All rights reserved.
//	This file is a part of the Xeres system.
//	Xeres 2007
//	Contact : xeres.engine@gmail.com
//	$(reservedInfo)
//	$(reservedDeclaration)
//	--------------------------------------------------------------------
///	@file	<CPythonInterpreter.cpp>
///	@path	~/src/python/interpreter/
///	@date	2007/12/07
///	@desc	Python interpreter implementation.

#include "config/config.h"

#include "python/python_plug.h"

#include "python/interpreter/CPythonInterpreter.h"

namespace xeres {

	IMPL_IOBJECT_CLASS( CPythonInterpreter );

	// ctor
	CPythonInterpreter::CPythonInterpreter( void )
		: m_multiline( 0 )
	{
	}

	// dtor
	CPythonInterpreter::~CPythonInterpreter( void )
	{
	}

	// QueryPrompt
	const WString& CPythonInterpreter::QueryPrompt( void )
	{
		static const WString s_pythonPrompt(	_S(">>>") );
		static const WString s_statementPrompt( _S("...") );

		if( m_multiline == 0 )
			return s_pythonPrompt;
		else
			return s_statementPrompt;
	}

	// RunInteractive
	InterpretResult CPythonInterpreter::RunInteractive( const WString& script , WString& cue )
	{
		// should initialize python plug before this
		XS_ASSERT( PythonPlug::instance().IsInitialized() );

		AString str;
		wcs_to_mbs( script , str );

		if( str.empty() || script == cue )
		{
			if( m_multiline == 0 )
			{
				// empty input
				return INTERPRET_EMPTY;
			}

			// not multi-line
			--m_multiline;
		}
		else
		{
			char last = str[ str.size() - 1 ];
			if( last == ':' || last == '\\' )
			{
				++m_multiline;
			}

			m_buffer += str + "\n";
		}

		cue.clear();
		if( m_multiline > 0 )
		{
			for( int i = 0 ; i < m_multiline ; ++i )
			{
				cue += _S("\t");
			}
		}

		if( m_multiline == 0 )
		{
			bool result = PythonPlug::instance().RunString( m_buffer.c_str() );
			m_buffer.clear();
			if( !result )
				return INTERPRET_FAILED;
			return INTERPRET_OK;
		}
		else
		{
			return INTERPRET_STMT;
		}
	}

	// BeginLex
	void * CPythonInterpreter::BeginLex( const WString& str )
	{
		return NULL;
	}

	// NextLex
	const LexAttr& CPythonInterpreter::NextLex( void * state , int& length )
	{
		return m_attrs[LEX_EOF];
	}

	// EndLex
	void CPythonInterpreter::EndLex( void * state )
	{

	}

} // namespace xeres
